package com.example.shw

import android.app.Service
import android.media.AsyncPlayer
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.ToggleButton

class AudioActivity : AppCompatActivity() {
    private lateinit var aManager: AudioManager
    private lateinit var mPlayer: MediaPlayer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_audio)
        aManager = getSystemService(Service.AUDIO_SERVICE) as AudioManager
        val play = findViewById<Button>(R.id.play)
        val up = findViewById<Button>(R.id.up)
        val down = findViewById<Button>(R.id.down)
        val mute = findViewById<ToggleButton>(R.id.mute)
        mPlayer = MediaPlayer.create(this@AudioActivity, R.raw.imhappy)
        mPlayer.isLooping = true
        play.setOnClickListener {
            if (!mPlayer.isPlaying) mPlayer.start()
            else {
                mPlayer.pause()
                mPlayer.seekTo(0)
            }
        }
        up.setOnClickListener {
            aManager.adjustStreamVolume(
                AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI
            )
        }
        down.setOnClickListener {
            aManager.adjustStreamVolume(
                AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI
            )
        }
        mute.setOnCheckedChangeListener { _, isChecked ->
            aManager.adjustStreamVolume(
                AudioManager.STREAM_MUSIC,
                if (isChecked) AudioManager.ADJUST_MUTE
                else AudioManager.ADJUST_UNMUTE,
                AudioManager.FLAG_SHOW_UI
            )
        }
    }
}